# -*- coding: utf-8 -*-
from sklearn.linear_model import LinearRegression


# -*- coding: utf-8 -*-

# 绘制所有区的生长期NDVI平均值和全年NDVI平均值，每幅图包括所有区的数据

import os
import json
import matplotlib.pyplot as plt
import numpy as np
from scipy.interpolate import make_interp_spline
from matplotlib import font_manager  # 导入字体管理模块
from statsmodels import api as sm


my_font = font_manager.FontProperties(fname="C:/WINDOWS/Fonts/STSONG.TTF")

plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号

label_font = {'family': 'serif',
        'color': 'black',
        'weight': 'normal',
        'size': 16,
        }

legend_font = {'family': "STSONG",
              # 'color': 'black',
              'weight': 'normal',
              'size': 15,
              }

with open("avgRecord.json") as f:
    data = json.load(f)
    d1 = data['QuNDVI_Excel']


def draw(title, fig, params, py):
    x = ['2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012', '2013',
         '2014', '2015', '2016', '2017', '2018', '2019', '2020']
    xx = np.arange(0, len(x), 1)
    xn = np.array(xx)
    x_smooth = np.linspace(xn.min(), xn.max(), 300)
    y = py
    y_year_avg = y['year_avg']
    y_growth_avg = y['growth_avg']
    y_year_avg_smooth = make_interp_spline(xn, y_year_avg)(x_smooth)
    y_growth_avg_smooth = make_interp_spline(xn, y_growth_avg)(x_smooth)
    plt__ = fig.add_subplot(params)
    plt__.plot(x_smooth, y_year_avg_smooth, label="年平均变化趋势")
    plt__.plot(x_smooth, y_growth_avg_smooth, label="生长期（4-10月）变化趋势")
    plt__.set_title("%sNDVI变化趋势图" % title, fontproperties = my_font,fontsize = 20, pad=20)

    plt__.set_xlabel("Year", fontdict=label_font)
    plt__.set_ylabel("NDVI", fontdict=label_font)
    plt__.legend(loc=2, prop=legend_font)
    plt__.grid(alpha=0.1, color='g', which="major")


def run(save_name, keys, fig, data):
    c = 721
    for i in keys:
        print(i)
        print(data[i])
        draw(title=i, fig=fig, params=c, py=data[i])
        c += 1
        t = ['2000', '2001', '2002', '2003', '2004', '2005', '2006', '2007', '2008', '2009', '2010', '2011', '2012',
             '2013',
             '2014', '2015', '2016', '2017', '2018', '2019', '2020']
        plt.xticks(np.arange(0, len(t), 1), t, fontproperties = 'Times New Roman', size = 14)
        plt.yticks(fontproperties='Times New Roman', size=14)
        plt.tight_layout(pad=8, w_pad=1.5, h_pad=8)
    plt.savefig(save_name)
    plt.clf()


def analyze(data: dict, key: dict.keys):
    """
    NDVI关于时间序列的线性回归分析
    data为一个包含生长期平均值和年平均值的字典
    :return 回归系数
    """
    x = np.array(np.arange(0, len(data.get("year_avg")), 1)).reshape(-1, 1)
    x = sm.add_constant(x)
    y = data.get(key)
    model = sm.OLS(y, x).fit()
    # print(model.summary(), file=f)
    # print("*#"*100, file=f)
    print(model.params)
    return model.params



if __name__ == '__main__':
    n1 = "E:\\毕设数据\\pictures\\行政区1.pdf"
    n2 = "E:\\毕设数据\\pictures\\行政区2.pdf"
    n = "E:\\毕设数据\\pictures\\UsingType.pdf"
    key = list(data["UsingTypeNDVI_Excel"])
    # key1 = list(d1)[:6]
    # key2 = list(d1)[6:]
    fig = plt.figure(figsize=(30, 90), dpi=160)
    # run(save_name=n1, fig=fig, keys=key1)
    # run(save_name=n2, fig=fig, keys=key2)
    # run(save_name=n, keys=key, fig=fig, data=data["UsingTypeNDVI_Excel"])
    d = data['WuhanNDVI_Excel']
    print(d)
    analyze(d)